package com.jt.aop;

import com.jt.annotation.CacheFind;
import com.jt.util.ObjectMapperUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

import java.util.Arrays;

@Aspect
@Component
public class RedisAspect {

    @Autowired
    //private Jedis jedis;
//    private ShardedJedis jedis;
    private JedisCluster jedis;

    //@Pointcut("bean(itemCatServiceImpl)")
    //@Pointcut("within(com.jt.service..*)")
    //@Pointcut("execution(* com.jt.service..*.*(..))")
    //@Pointcut("execution(int com.jt.service..*.add*(String))")
//	@Pointcut("@annotation(cacheFind)")
//	public void doAspect() {
//	}

    @Before("@annotation(com.jt.annotation.CacheFind)")
    public void before(JoinPoint jp) {
        Object target = jp.getTarget();//获取目标对象
        Object[] args = jp.getArgs();//获取方法的参数值
        Signature signature = jp.getSignature(); //方法签名
        String targetName = signature.getDeclaringTypeName();
    }

    @Around("@annotation(cacheFind)")
    public Object doAround(ProceedingJoinPoint jp, CacheFind cacheFind) {
        long start = System.currentTimeMillis();
        Object proceed = null;
        String key = cacheFind.key();
        key += "::" + Arrays.toString(jp.getArgs());
        if (!jedis.exists(key)) {
            try {
                proceed = jp.proceed();
                long end = System.currentTimeMillis();
                String json = ObjectMapperUtil.getJson(proceed);
                if (cacheFind.seconds() > 0) {
                    jedis.setex(key, cacheFind.seconds(), json); //向redis缓存存入数据
                } else {
                    jedis.set(key, json); //向redis缓存存入数据
                }
                System.out.println("第一次查询数据库 耗时:" + (end - start));
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                throw new RuntimeException(throwable);
            }
        } else {
            String json = jedis.get(key);
            MethodSignature signature = (MethodSignature) jp.getSignature();

            proceed = ObjectMapperUtil.getObject(json, signature.getReturnType());
            long end = System.currentTimeMillis();
            System.out.println("获取redis缓存 耗时:" + (end - start));
        }

        return proceed;
	}
}
